import os
from fastapi import APIRouter, Depends, File, UploadFile, HTTPException, status
from pydantic import BaseModel
from app.crud.user import create_expectation, create_user, get_users_by_role, update_expectation, update_user, upload_avatar,get_user_by_id, upload_resume
from app.dependencies import require_role
from app.middlewares.auth_middleware import create_access_token, create_refresh_token, get_current_user
from app.models.job import Job
from app.models.user import Expectation, Resume, User, UserRole
from app.schemas.user import ExpectationInDB, ExpectationUpdate, JobInDB, TokenResponse, UserBeas, LoginRequest, UserCreate, UserInDB, UserOccupied, UserUpdate
from app.settings import MEDIA_BASE_PATH

# 创建用户路由
router = APIRouter()


@router.post("/login", summary="用户登录")
async def login(login_data: LoginRequest):
    """
    用户登录
    
    权限要求:
    - 无需认证
    
    参数:
    - login_data: LoginRequest, 包含登录信息的请求体
    
    返回:
    - TokenResponse: 包含访问令牌和用户基本信息的响应
    
    异常:
    - 401 Unauthorized: 如果用户名/邮箱或密码错误时抛出
    """
    # 查找用户
    user = await User.get_or_none(phone=login_data.phone) if login_data.phone else await User.get_or_none(email=login_data.email)
    
    if not user or not user.verify_password(login_data.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名/邮箱或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 验证密码
    if not user.verify_password(login_data.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 创建访问令牌
    access_token = create_access_token(data={"id": user.id})
    refresh_token = create_refresh_token(data={"id": user.id})

    return {
        "access_token": access_token,
        "user": UserBeas.model_validate(user.__dict__)
    }


@router.post("/register", response_model=UserCreate, summary="用户注册")
async def register(user: UserCreate):
    """
    用户注册
    
    权限要求:
    - 无需认证
    
    参数:
    - user: UserCreate, 包含用户注册信息的请求体
    - job_seeker_status：1:离职正在找工作 2:在职急需工作 3:在职找工作 4:在职没有找工作的打算
    
    返回:
    - 注册成功的用户基本信息
    
    异常:
    - 400 Bad Request: 如果用户名、邮箱或手机号已存在时抛出
    """
    # 检查用户名是否已存在
    existing_user = await User.get_or_none(username=user.username)
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在",
        )
        
    # 检查邮箱是否已存在
    existing_email = await User.get_or_none(email=user.email)
    if existing_email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="邮箱已存在",
        )
        
    # 检查手机号是否已存在
    if user.phone:
        existing_phone = await User.get_or_none(phone=user.phone)
        if existing_phone:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="手机号已存在",
            )
            
    # 创建用户
    try:
        new_user = await create_user(user)
        return UserCreate.model_validate(new_user.__dict__)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"用户创建失败: {str(e)}"
        )


@router.post("/upload_avatar", summary="上传用户头像")
async def upload_avatar_route(
    file: UploadFile = File(...),
    current_user: UserOccupied = Depends(get_current_user)
):
    """
    上传用户头像
    
    权限要求:
    - 需要登录
    
    参数:
    - file: UploadFile, 上传的文件对象
    - current_user: UserOccupied, 当前登录用户信息
    
    返回:
    - 包含头像路径的字典
    
    异常:
    - 400 Bad Request: 如果上传的文件不是图片时抛出
    """
    # 检查文件类型是否为图片
    if not file.content_type.startswith("image/"):
        raise HTTPException(
            status_code=400,
            detail="只能上传图片文件"
        )
    
    # 读取文件内容
    file_content = await file.read()
    
    # 调用CRUD函数上传头像
    avatar_path = await upload_avatar(current_user.username, file_content)
    
    # 更新用户头像路径
    user = await User.get(id=current_user.id)
    user.avatar = avatar_path
    await user.save()
    
    return {"avatar_path": avatar_path}


@router.get("/", summary="获取所有用户", dependencies=[Depends(get_current_user)])
async def get_all_users(
    skip: int = 0, 
    limit: int = 10, 
    current_user: UserOccupied = Depends(get_current_user)
    ):
    """
    获取所有用户信息
    
    权限要求:
    - 需要超级管理员权限
    
    参数:
    - skip: int, 跳过的记录数，用于分页
    - limit: int, 每页显示的记录数
    - current_user: UserOccupied, 当前登录用户信息
    
    返回:
    - 包含用户列表和分页信息的字典
    
    异常:
    - 403 Forbidden: 如果当前用户不是超级管理员时抛出
    """

    # 检查当前用户是否为超级管理员
    if current_user.role != UserRole.SUPER_ADMIN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有超级管理员可以访问此资源"
        )
    
    # 获取分页用户数据
    users_query = User.all()
    total = await users_query.count()
    users = await users_query.offset(skip).limit(limit)
    
    return {
        "total": total,
        "skip": skip,
        "limit": limit,
        "users": [UserInDB.model_validate(user.__dict__) for user in users]
    }




@router.put("/{user_id}", summary="修改用户信息", dependencies=[Depends(get_current_user)])
async def update_user_info(
        user_id: int,
        user_update: UserUpdate,
        current_user: UserOccupied = Depends(get_current_user),
        _=Depends(require_role([UserRole.SUPER_ADMIN, UserRole.RECRUITER, UserRole.JOB_SEEKER]))
    ):
        """
        修改用户信息
        
        权限要求:
        - 需要登录
        - 超级管理员可以修改任何用户
        - 普通用户只能修改自己的信息
        
        参数:
        - user_id: int, 用户ID
        - user_update: UserUpdate, 需要更新的用户信息
        - current_user: UserOccupied, 当前登录用户信息
        
        返回:
        - 更新后的用户信息
        
        异常:
        - 403 Forbidden: 如果普通用户尝试修改其他用户信息时抛出
        - 404 Not Found: 如果用户不存在时抛出
        """
        # 检查权限：普通用户只能修改自己的信息
        if (current_user.role in [UserRole.JOB_SEEKER, UserRole.RECRUITER] and 
            user_id != current_user.id):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权修改其他用户信息"
            )
        
        # 更新用户信息
        user = await update_user(user_id, user_update)
        
        return UserInDB.model_validate(user.__dict__)


@router.get("/recruiters", summary="获取招聘者列表", dependencies=[Depends(get_current_user)])
async def get_recruiters(
    skip: int = 0, 
    limit: int = 10, 
    _=Depends(require_role([UserRole.SUPER_ADMIN]))
):
    """
    获取所有招聘者用户列表
    
    权限要求:
    - 需要超级管理员权限
    
    参数:
    - skip: int, 跳过的记录数，用于分页
    - limit: int, 每页返回的记录数
    
    返回:
    - List[UserInDB]: 招聘者用户列表，包含完整用户信息
    """
    recruiters = await get_users_by_role(UserRole.RECRUITER, skip= skip, limit= limit)
    result = []
    for recruiter in recruiters:
        recruiter_data = UserInDB.model_validate(recruiter.__dict__)
        jobs = await Job.filter(creator_id=recruiter.id).all()
        result.append({
            "user": recruiter_data,
            "jobs": [JobInDB.model_validate(job.__dict__) for job in jobs]
        })
    return result


@router.get("/job_seekers", summary="获取求职者列表", dependencies=[Depends(get_current_user)])
async def get_job_seekers(
    skip: int = 0, 
    limit: int = 10, 
    _=Depends(require_role([UserRole.SUPER_ADMIN]))
):
    """
    获取所有求职者用户列表
    
    权限要求:
    - 需要超级管理员权限
    
    参数:
    - skip: int, 跳过的记录数，用于分页
    - limit: int, 每页返回的记录数
    
    返回:
    - List[UserInDB]: 求职者用户列表，包含完整用户信息
    """
    job_seekers = await get_users_by_role(UserRole.JOB_SEEKER, skip= skip, limit= limit)
    result = []
    for job_seeker in job_seekers:
        job_seeker_data = UserInDB.model_validate(job_seeker.__dict__)
        expectation = await Expectation.get_or_none(user=job_seeker)
        result.append({
            "user": job_seeker_data,
            "expectation": ExpectationInDB.model_validate(expectation.__dict__) if expectation else None
        })
    return result

@router.get("/{user_id}", summary="获取用户详情", dependencies=[Depends(get_current_user)])
async def get_user_detail(
    user_id: int,
    current_user: UserOccupied = Depends(get_current_user)
):
    """
    获取用户详情信息
    
    权限要求:
    - 需要登录
    - 超级管理员可以查看任何用户
    - 普通用户只能查看自己的信息
    
    参数:
    - user_id: int, 用户ID (传入0表示获取当前登录用户自己的信息)
    - current_user: UserOccupied, 当前认证用户信息
    
    返回:
    - dict: 包含用户基本信息和相关数据的字典，包括:
        - 用户详情 (UserInDB)
        - 简历URL (如果有)
        - 求职期望 (如果是求职者)
        - 创建的工作列表 (如果是招聘者)
    
    异常:
    - 403 Forbidden: 当普通用户(JOB_SEEKER/RECRUITER)尝试查看其他用户信息时
    - 404 Not Found: 当指定用户不存在时
    """
    resume_url = None
    expectation = None
    jobs = None
    if user_id == 0:
        user_id = current_user.id
    
    
    # 检查权限：普通用户只能查看自己的信息
    if (current_user.role == UserRole.JOB_SEEKER or current_user.role == UserRole.RECRUITER) and user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权查看其他用户信息"
        )
    
        # 获取用户信息
    user = await get_user_by_id(user_id)
    # 获取用户简历路径
    resume = await Resume.get_or_none(user=user)
    if resume:
        resume_url = resume.resume_url

    # 获取用户求职期望
    if current_user.role == UserRole.JOB_SEEKER:
        expectation = await Expectation.get_or_none(user=user)
        if expectation:
            expectation = ExpectationInDB.model_validate(expectation.__dict__)

    # 如果是招聘者，获取其创建的工作列表
    if current_user.role == UserRole.RECRUITER:
        jobs = await Job.filter(creator_id=user_id).all()
        jobs = [JobInDB.model_validate(job.__dict__) for job in jobs]
    
    user_data = UserInDB.model_validate(user.__dict__).model_dump()
    if MEDIA_BASE_PATH == os.path.join(os.getcwd()):
        user_data["avatar"] = os.path.join(user.avatar) if user.avatar else None
    else:
            user_data["avatar"] = os.path.join(user.avatar) if user.avatar else None
    
    return {
        **user_data,
        "expectation": expectation,
        "jobs":jobs
    }

@router.post("/upload-resume", 
             summary="上传简历", 
             dependencies=[Depends(get_current_user)])
async def upload_user_resume(
    file: UploadFile = File(...),
    current_user: UserOccupied = Depends(get_current_user),
     _=Depends(require_role([UserRole.JOB_SEEKER]))
):
    """
    上传用户简历文件
    
    权限要求:
    - 需要求职者权限
    
    参数:
    - file: UploadFile, 简历文件
    - current_user: UserOccupied, 当前登录用户信息
    
    返回:
    - dict: 包含简历存储路径的字典
    
    异常:
    - 400 Bad Request: 如果文件不是PDF格式时抛出
    - 500 Internal Server Error: 如果上传失败时抛出
    """
    # 检查文件类型
    if file.content_type != "application/pdf":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只支持PDF格式的简历"
        )
    
    # 读取文件内容
    file_content = await file.read()
    
    try:
        # 调用CRUD层方法上传简历
        resume_path = await upload_resume(current_user.username, file_content)
        return {"resume_url": resume_path}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"简历上传失败: {str(e)}"
        )
    
@router.post(
    "/expectations",
    summary="创建求职期望",
    dependencies=[Depends(get_current_user)]
)
async def create_user_expectation(
    expectation: ExpectationUpdate,
    current_user: UserOccupied = Depends(get_current_user),
    _=Depends(require_role([UserRole.JOB_SEEKER]))
):
    """
    创建用户的求职期望信息
    
    权限要求:
    - 需要求职者权限
    
    参数:
    - expectation: ExpectationUpdate, 求职期望信息
    - current_user: UserOccupied, 当前登录用户信息
    
    返回:
    - ExpectationInDB: 创建的求职期望信息
    
    异常:
    - 400 Bad Request: 如果期望薪资为负数时抛出
    - 404 Not Found: 如果用户不存在时抛出
    - 500 Internal Server Error: 如果创建失败时抛出
    """
    # try:
    #     # 检查用户是否已有期望信息
    #     existing_expectation = await Expectation.get_or_none(user_id=current_user.id)
    #     if existing_expectation:
    #         raise HTTPException(
    #             status_code=status.HTTP_400_BAD_REQUEST,
    #             detail="用户已有期望信息，请先更新或删除现有期望"
    #         )

    #     # 调用CRUD层方法创建期望
    #     created_expectation = await create_expectation(current_user.id, expectation)
    #     return ExpectationInDB.model_validate(created_expectation.__dict__)
    # except HTTPException as e:
    #     raise e
    # except Exception as e:
    #     raise HTTPException(
    #         status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
    #         detail=f"创建求职期望失败: {str(e)}"
    #     )
    try:
        # 检查用户是否已有期望信息
        existing_expectation = await Expectation.get_or_none(user_id=current_user.id)
        if existing_expectation:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户已有期望信息，请先更新或删除现有期望"
            )

        # 调用CRUD层方法创建期望
        created_expectation = await create_expectation(current_user.id, expectation)
        return ExpectationInDB.model_validate(created_expectation.__dict__)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建求职期望失败: {str(e)}"
        )



